//
//  MJTabbar.m
//  新浪微博
//
//  Created by mj on 13-4-21.
//  Copyright (c) 2013年 itcast. All rights reserved.
//

#import "MJTabbar.h"
#import "MJTabbarItem.h"

@interface MJTabbar() {
    // 当前被选中的tabbaritem
    MJTabbarItem *_current;
}
@end

@implementation MJTabbar

#pragma mark item点击
- (void)itemClick:(MJTabbarItem *)new {
    // 1.回调
    if (_itemClick) {
        _itemClick(new.tag);
    }
    
    // 2.改变状态
    _current.selected = NO;
    new.selected = YES;
    
    // 3.设置新的选中
    _current = new;
}

#pragma mark 构造方法
- (id)initWithFrame:(CGRect)frame
{
    if (self = [super initWithFrame:frame]) {
        // 设置tabbar背景
        self.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"tabbar_background.png"]];
    }
    return self;
}

#pragma mark 调整子控件的位置
- (void)adjustSubviews
{
    // 1.基本属性
    int count = self.subviews.count;
    CGFloat itemWidth = self.frame.size.width/count;
    CGFloat itemHeight = self.frame.size.height;
    
    // 2.调整
    for (int i = 0; i<count; i++) {
        MJTabbarItem *item = self.subviews[i];
        item.tag = i;
        item.frame = CGRectMake(itemWidth * i, 0, itemWidth, itemHeight);
        
        if (i == 0) {
            _current = item;
            _current.selected = YES;
        }
    }
}

#pragma mark 添加一个选项卡 
- (void)addTabWithTitle:(NSString *)title icon:(NSString *)icon
{
    // 1.添加item
    MJTabbarItem *item = [[MJTabbarItem alloc] init];
    [item setTitle:title icon:icon];
    [self addSubview:item];
    
    // 2.添加监听器
    [item addTarget:self action:@selector(itemClick:) forControlEvents:UIControlEventTouchDown];
    
    // 3.调整子控件的位置
    [self adjustSubviews];
}
@end